/**
 * 
 */
package de.peacei.android.ioex_notesapp;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * @author Matthias
 * 
 */
public class AccountListActivity extends ListActivity {
    protected AccountManager accountManager;
    protected Intent intent;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        accountManager = AccountManager.get(getApplicationContext());
        
        Account[] accounts = accountManager.getAccountsByType("com.google");
        
        this.setListAdapter(new AccountAdapter(accounts));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        
        Account account = (Account) getListView().getItemAtPosition(position);
        
        Intent intent = new Intent(this, IOEx_NotesAppActivity.class);
        intent.putExtra("account", account);
        
        startActivity(intent);
        
        this.finish();
    }
    
    private class AccountAdapter extends BaseAdapter {
        
        private Account[] accounts;
        
        public AccountAdapter(Account[] accounts) {
            super();
            this.accounts = accounts;
        }
        
        @Override
        public int getCount() {
            return accounts.length;
        }

        @Override
        public Account getItem(int position) {
            return this.accounts[position];
        }

        @Override
        public long getItemId(int position) {
            return Long.valueOf(this.accounts[position].hashCode());
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            TextView view = (TextView) inflater.inflate(R.layout.list_item, null);
            view.setText(accounts[position].name);
            return view;  
        }
        
    }
}
